//
//  LZMyPersonInfoViewController.m
//  laziz_Consumer
//
//  Created by ZhaoDongBo on 2016/10/27.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZMyPersonInfoViewController.h"
#import "LZMyChangeInfoViewController.h"
#import "LZRestaurantInfoViewController.h"
#import "LZCompanyInfoViewController.h"

#import "LZMyPersonInfoTableView.h"
#import "LZImagePickerManager.h"

#import "GVUserDefaults+LZProperties.h"
#import "LZActionSheet.h"

#import "Masonry.h"
#import "LZUserModel.h"
#import "extobjc.h"

#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>

#import "LZUploadImagePresenter.h"
#import "LZUserInfoPresenter.h"
#import "LZAlertView.h"
#import "LZRemindView.h"
#import "LZRestaurantAuthenticationViewController.h"
#import "LZLinkOrEditEmailViewController.h"
#import "LZManagePicturesViewController.h"

@interface LZMyPersonInfoViewController () <UINavigationControllerDelegate, UIImagePickerControllerDelegate, LZPictureManagerDelegate>

@property (nonatomic, strong) LZMyPersonInfoTableView * tableView;
@property (nonatomic, weak) LZActionSheet           * actionSheet;

@property (strong, nonatomic) LZImagePickerManager  * pictureManager;
@property (strong, nonatomic) LZUserInfoPresenter   * userInfoPresenter;
@property (strong, nonatomic) LZUploadImagePresenter* uploadImagePresenter;

@end

@implementation LZMyPersonInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.umLogPageViewName = @"个人信息页面";
    self.title = LZLocalizedString(@"personal_info", nil);
    self.view.backgroundColor = UIColorFromRGB(0xffffff, 1);
    self.userInfoPresenter = [[LZUserInfoPresenter alloc] init];
    self.uploadImagePresenter = [[LZUploadImagePresenter alloc] init];
    
    [self setup];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setup {
    
    WS(weakSelf);
    
    [self.view addSubview:self.tableView];
    [self.tableView makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.leading.mas_equalTo(0);
        make.trailing.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    
       
    self.tableView.didSelectRowBlock = ^(NSIndexPath * indexPath) {
        
        NSInteger section = indexPath.section;
        NSInteger row = indexPath.row;
        UIViewController *vc;        
        if (section == 0) {
            
            if (row == 1 || row == 2) {
                if ([GVUserDefaults standardUserDefaults].authType == kAuthType_noneAuth) {
                    LZRestaurantAuthenticationViewController* vc = [[LZRestaurantAuthenticationViewController alloc] init];
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                    return;
                }else if([GVUserDefaults standardUserDefaults].authType == kAuthType_waitAuth){
                    LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"res_auth_wait", nil) andImage:nil cancelButtonTitle:nil otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
                    [alert show];
                    return;
                }else if([GVUserDefaults standardUserDefaults].authType == kAuthType_rejectAuth){
                    LZRestaurantAuthenticationViewController* vc = [[LZRestaurantAuthenticationViewController alloc] init];
                    vc.regected = YES;
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                    return;
                }
            }
            
            if (row == 0) {
                if ([GVUserDefaults standardUserDefaults].authType == kAuthType_noneAuth) {
                    LZRestaurantAuthenticationViewController* vc = [[LZRestaurantAuthenticationViewController alloc] init];
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                    return;
                }else if([GVUserDefaults standardUserDefaults].authType == kAuthType_waitAuth){
                    LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"res_auth_wait", nil) andImage:nil cancelButtonTitle:nil otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
                    [alert show];
                    return;
                }else if([GVUserDefaults standardUserDefaults].authType == kAuthType_rejectAuth){
                    LZRestaurantAuthenticationViewController* vc = [[LZRestaurantAuthenticationViewController alloc] init];
                    vc.regected = YES;
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                    return;
                }
                
                [weakSelf.actionSheet ReloadTableViewArrayTitle:@[@[LZLocalizedString(@"change_takephoto", nil), LZLocalizedString(@"change_choosephoto", nil),LZLocalizedString(@"person_choose_restaurant_photo", nil)], @[LZLocalizedString(@"cancel", nil)]]];
                [weakSelf.actionSheet ShowView];
                
            } else if (row == 1) {
                vc = [[LZRestaurantInfoViewController alloc] init];
                
            } else {
                vc = [[LZCompanyInfoViewController alloc] init];
            }
        }
        else {
            if (section == 1) {
                switch (row) {
                    case 0:{
                        if ([GVUserDefaults standardUserDefaults].isSetPassword == YES){
                            vc = [weakSelf createChangeInfoWithType:LZ_MYCHANGEINFO_TYPE_CHANGEPASSWORD];
                        } else {
                            vc = [weakSelf createChangeInfoWithType:LZ_MYCHANGEINFO_TYPE_SETPASSWORD];
                        }
                    }
                        break;
                    case 1:
                        if ([GVUserDefaults standardUserDefaults].cellphone.length > 0) {
                            vc = [weakSelf createChangeInfoWithType:LZ_MYCHANGEINFO_TYPE_IDCHECK_MOBILE];
                        }else{
                            vc = [weakSelf createChangeInfoWithType:LZ_MYCHANGEINFO_TYPE_LINKNEW_MOBILE];
                        }
                        
                        break;
                    case 2:{
                        LZLinkOrEditEmailViewController *emailVC = [[LZLinkOrEditEmailViewController alloc] initWithNibName:@"LZLinkOrEditEmailViewController" bundle:nil];
                        if ([GVUserDefaults standardUserDefaults].email.length > 0) {
                            emailVC.isLinkEmail = NO;
                        }else{
                            emailVC.isLinkEmail = YES;
                        }
                        
                        [weakSelf.navigationController pushViewController:emailVC animated:YES];
                    }
                        
                    default:
                        break;
                }
            }
        }
        
        if (vc) {
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
    };
}

- (LZMyChangeInfoViewController *)createChangeInfoWithType:(LZ_MYCHANGEINFO_TYPE)type {
    
    LZMyChangeInfoViewController *vc = [[LZMyChangeInfoViewController alloc] init];
    vc.type = type;
    return vc;
}

#pragma mark - Setter/Getter

- (LZMyPersonInfoTableView *)tableView {
    
    if (_tableView == nil) {
        _tableView = [[LZMyPersonInfoTableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.dataArrays = @[LZLocalizedString(@"restaurant_info", nil),
                                  LZLocalizedString(@"company_info", nil),
                                  LZLocalizedString(@"password", nil),
                                  LZLocalizedString(@"mobile_phone", nil),
                                  LZLocalizedString(@"login_email", nil)];
    }
    
    return _tableView;
}

- (LZActionSheet *)actionSheet {
    if (_actionSheet == nil) {
        LZActionSheet *sheet = [[LZActionSheet alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _actionSheet = sheet;
        [_actionSheet creatHeaderWithTitle:LZLocalizedString(@"change_photo_title", nil) andHeight:41];
        [[UIApplication sharedApplication].keyWindow addSubview:_actionSheet];
        
        WS(weakSelf);
        _actionSheet.ClickSheetBlock = ^(NSIndexPath *indexPath, id obj) {
            if (indexPath.section == 0) {
                [weakSelf LASheetClickedButtonAtIndex:indexPath.row];
            }
        };
    }
    
    return _actionSheet;
}

- (void)LASheetClickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIImagePickerControllerSourceType sourceType = 0;
    
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        if (buttonIndex == 0) {
            // TakePhotos
            sourceType = UIImagePickerControllerSourceTypeCamera;
        } else if (buttonIndex == 1) {
            // PhotoAlbums
            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }else if (buttonIndex == 2){
        
            LZManagePicturesViewController *vc = [[LZManagePicturesViewController alloc] initWithNibName:@"LZManagePicturesViewController" bundle:nil];
            [self.navigationController pushViewController:vc animated:YES];
            @weakify(self);
            [vc setSelectPictureBlock:^(NSString *imageUrl) {
                @strongify(self)
                imageUrl = [imageUrl stringByReplacingOccurrencesOfString:APIBaseImageUrl withString:@""];
                NSArray *arr = [imageUrl componentsSeparatedByString:@"&&"];
                [self changePersonIconWithImgURL:arr[0]];
            }];
            
            return;
        }
        
    } else {
        if (buttonIndex == 0) {
            return;
        } else {
            sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        }
    }
    
    [self.pictureManager choosePictureWithSourceType:sourceType andPresenterVC:self];
}   

#pragma mark - pictureManager的GET方法
- (LZImagePickerManager*)pictureManager {
    if (_pictureManager) {
        return _pictureManager;
    }
    LZImagePickerManager *manager = [[LZImagePickerManager alloc] init];
    manager.allowsEditing = YES;
    manager.delegate = self;
    _pictureManager = manager;
    return _pictureManager;
}

#pragma mark - LZPictureManagerDelegate
- (void)LZPictureManagerFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *aImage = [info objectForKey:UIImagePickerControllerEditedImage];
    if (aImage) {
        [self requestUploadImage:aImage];
    }
}

- (void)requestUploadImage:(UIImage*)aImage {
    WS(weakSelf)
    //上传头像
    
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
    
    [self.uploadImagePresenter uploadImage:aImage
                             andBusinessId:[LZUserModel Instance].userId
                           andBusinessType:@"2"
                             andBusinessNo:@"1"
                                andIsThumb:NO
                                   andSize:CGSizeZero
                              andonSuccess:^(id data) {
                                  DLog(@"上传头像 %@", data);
                                  [weakSelf stopLoadingViewForView:weakSelf.view];
                                  //保存到服务器
                                  NSArray *resultArray = data[@"data"];
                                  if (resultArray.count>0) {
                                      NSDictionary *dic = resultArray[0];
                                      NSString *filePath = dic[@"filePath"];
                                      
                                      [weakSelf changePersonIconWithImgURL:filePath];
                                      
                                  }
                              } onFail:^(NSString *fail) {
                                  [weakSelf stopLoadingViewForView:weakSelf.view];
                                  
                                  [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"]
                                                   andContent:LZLocalizedString(@"change_failed", nil)];
                                  
                              }];
}


- (void)changePersonIconWithImgURL:(NSString *)filePath
{
    @weakify(self);
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
    [self.userInfoPresenter userChangeHeadImageFilePath:filePath andonSuccess:^(id data) {
        
        @strongify(self);
        [self stopLoadingViewForView:self.view];
        
        DLog(@"保存到服务器 %@", data);
        [LZUserModel Instance].userInfo.sellerPhoto = filePath;
        [LZUserModel Instance].merchantInfo.sellerPhoto = filePath;
        
//        [[LZDatabase dataManager] updateByUserId:[LZUserModel Instance].userId andImageUrl:filePath];
//        [[LZDatabase dataManager] updateBySellerId:[LZUserModel Instance].sellerId andImageUrl:filePath];
        [self.tableView reloadData];
        
        [LZRemindView initWithImage:[UIImage imageNamed:@"提示对勾"]
                         andContent:LZLocalizedString(@"change_success", nil)];
        
    } onFail:^(NSString *fail) {
        @strongify(self);
        [self stopLoadingViewForView:self.view];
        [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"]
                         andContent:LZLocalizedString(@"change_failed", nil)];
    }];

}
@end
